<?php

namespace app\common\model\logic;

class RolesBindModel
{
    public function __construct()
    {
        $this->curModel = model('dao.roles_bind');
    }

    public function getAdminBind($data)
    {
        $where[] = ['target_id', '=', $data['id']];
        $where[] = ['target_type', '=', 1];

        return $this->getBind($where);
    }

    public function saveAdminBind($data)
    {
        $data['type'] = 1;
        $this->clearRoles($data);

        return $this->saveBind($data);
    }

    private function clearRoles($data)
    {
        $where['target_type'] = $data['type'];
        $where['target_id'] = $data['id'];
        $bindList = $this->curModel->where($where)->select();
        if (!$bindList->isEmpty()) {
            $ids = [];
            foreach ($bindList as $ve) {
                $ids[] = $ve['id'];
            }
            $this->curModel->destroy($ids);
        }
    }

    private function saveBind($data)
    {
        $roleList = explode(',', $data['roles_list']);
        $insertData = [];
        foreach ($roleList as $ve) {
            $insertRow['target_type'] = $data['type'];
            $insertRow['target_id'] = $data['id'];
            $insertRow['roles_id'] = $ve;
            $insertRow['status'] = 1;
            $insertData[] = $insertRow;
        }
        $result = $this->curModel->saveAll($insertData);
        if ($result !== false) {
            return  $result;
        } else {
            exception('角色绑定失败', 0, 'app\\common\\exception\\AccountException');
        }
    }

    private function getBind($where)
    {
        $bindList = $this->curModel->where($where)->all();
        if ($bindList->isEmpty()) {
            exception(lang('AUTH_NOT'), 0, 'app\\common\\exception\\LogicException');
        } else {
            $ids = [];
            foreach ($bindList as $ve) {
                $ids[] = $ve['roles_id'];
            }

            return $ids;
        }
    }
}
